library(JavaGD)
library(grid)   
library(lattice)    
library(latticeExtra)
library(reshape)
	
selected_dat = read.table("all-cell-output.csv")
dat = read.table("all-cell-output.csv")
str(dat)

plot_viz_x <- function(xName, yName, condXName, grouping, heatmapMetric) {

	
	print('1 Make syntactically valid names')
	xName = make.names(xName)
	yName = make.names(yName)
	condXName = make.names(condXName)

	print('2 Extract column with names from selected_dat')
	x  <-  selected_dat[[xName]]
	y  <-  selected_dat[[yName]]	
	condX = selected_dat[[condXName]]

	print('3 Set default trellist parameters')	
	trellis.par.set( axis.line = list(lwd=1) )
	trellis.par.set("strip.border" = list(col="black"))

	print('4 Parse grouping and heatmapMetric')
	heatmap_metric_parsed = parse(text = heatmapMetric)	
	num_cols = max(selected_dat$X.run.number.) / max(selected_dat$run.counter)
	if (nchar(grouping) != 0)
	{ grouping_parsed = parse(text = grouping)}
	else
	{ grouping_parsed = NULL}
	
	print('5 plot_viz_x xyplot')	
	#selected_dat <<- subset(dat, run.counter %in% c(5))
	v =	xyplot(y ~ x | condX,
			data = selected_dat,
			#groups = X.run.number.,
			#groups = run.counter,
			#distribute.type = TRUE,
			type = "l",
			#pch = ".",
			#groups = grouping_parsed,
			scales = list(draw = FALSE),
			#type = "l",
			#strip = FALSE,
			strip = strip.custom(
					strip.levels = TRUE,
					strip.names = FALSE,
					sep = ' * ',
					bg = 'white',
					fg = 'white'),
			#col = brewer.pal(8,"Set1")[selected_dat$run.counter],
			#xlab = condXName,
			#aspect = num_cols/2,
			#auto.key = list(space = "right"),
			#layout = c(0, num_cols),
			#par.settings=list(
			#		border = TRUE,
			#		layout.widths=list(left.padding=0, right.padding=0),
			#		layout.heights=list(top.padding=0, bottom.padding=0)
			#),
			#scales = list(x = list(relation="free")),
			panel = function(...) {
#				#panel.groups =  dat$X.run.number.
#				l <- list(...) # Put the arguments in a (named) list
#				#str(l)
#				#print(summary(l))
#				#print(selected_dat[l$subscript]$X.run.number)
#				print("l$subscript")			
#				print(l$subscript)
#				print("selected_dat[1]$X.run.number")
#				#panel.groups= selected_dat[l$subscript,]$X.run.number.
#				#TODO: handle statements with with syntactically invalid names 
#				#for (i in seq(along = l)) 
#				#{
#				#		cat("Argument ", i, " name:", names(l)[i], "Value:", l[[i]], "\n")		   
#				#}
#				panel <- data.frame(l[1:3])	
#				avg = eval(heatmap_metric_parsed)
#				# Put gray squares or dotted texture if NaN
				if (!is.nan(avg))
				{
#					panel.fill(col = rgb(avg,avg,avg))
					panel.superpose( ...)
				}
#				else
#				{
#					panel.grid(col = "gray",lty = 1)
#				}
#			}
	)
	print(v)
	viz <<- v
}

plot_viz_x("X.step.", "percent.burned", "density", "", "mean(panel$y)/max(y)")